//
//  GLCustomCell.m
//  GLCustomCell
//
//  Created by 121 on 2017/9/22.
//  Copyright © 2017年 杭州吉利控股信息中心. All rights reserved.
//


#import "GLCustomCell.h"
#import "GLBadgeLabel.h"
#if __has_include("UIImageView+WebCache.h")
#import "UIImageView+WebCache.h"
#endif
#import "Masonry.h"
#define GLCustomCellSubConentKey @"GLCustomCellSubConentKey"
#define GLCustomCellMargin 15
#define GLCustomCellControlMargin 8


//可根据此key给CELL本身设置属性，仅供设置属性
NSString*_Nonnull GLCustomCellSelf = @"GLCustomCellSelf";
/*
 可添加组件 GLCustomCellTextKey
 */

/*
 @class GLCustomLabel
 默认keypath:.text
 value:@NSString
*/
NSString*_Nonnull GLCustomCellText = @"GLCustomCellText";    //文字
NSString*_Nonnull GLCustomCellGrayText = @"GLCustomCellGrayText";    //文字
NSString*_Nonnull GLCustomCellText2 = @"GLCustomCellText2";    //文字
NSString*_Nonnull GLCustomCellCenterText = @"GLCustomCellCenterText";    //文字 居中
NSString*_Nonnull GLCustomCellSubText = @"GLCustomCellSubText";    //文字
NSString*_Nonnull GLCustomCellCatpionText = @"GLCustomCellCatpion";          // 文字
/*
 @class GLCustomImageView
 默认keypath:.image
 value:@NSString @UIImage
 */
NSString*_Nonnull GLCustomCellIcon = @"GLCustomCellIcon";         //图标
NSString*_Nonnull GLCustomCellIcon2 = @"GLCustomCellIcon2";      //图标2
/*
 @class UISwitch
 默认keypath:.on
 value:@NSNumber
 */
NSString*_Nonnull GLCustomCellSwitch = @"GLCustomCellSwitch";  //开关
/*
 @class UITextField
 默认keypath:.text
 value:@NSString
 */
NSString*_Nonnull GLCustomCellInput = @"GLCustomCellInput";      //输入框
NSString*_Nonnull GLCustomCellLeftNoEditInput = @"GLCustomCellLeftNoEditInput";      //输入框 不可编辑 靠左排列
NSString*_Nonnull GLCustomCellRightNoEditInput = @"GLCustomCellRightNoEditInput";      //输入框 不可编辑 靠右排列
/*
 @class UITextView
 默认keypath:.text
 value:@NSString
 */
NSString*_Nonnull GLCustomCellTextView = @"GLCustomCellTextView";      //多行显示textView
/*
 @class GLBadgeLabel
 默认keypath:.text
 value:@NSString
 */
NSString*_Nonnull GLCustomCellBadge = @"GLCustomCellBadge";      //badge角标
/*
 @class GLCustomButton
 默认keypath:.title .image
 value:@NSString @UIImage
 */
NSString*_Nonnull GLCustomCellButton = @"GLCustomCellButton";      //按钮1
NSString*_Nonnull GLCustomCellButton2 = @"GLCustomCellButton2";      //按钮2
NSString*_Nonnull GLCustomCellButton3 = @"GLCustomCellButton3";      //按钮3
NSString*_Nonnull GLCustomCellButton4 = @"GLCustomCellButton4";      //按钮4
NSString*_Nonnull GLCustomCellButton5 = @"GLCustomCellButton5";      //按钮5
//cell自带
NSString*_Nonnull GLCustomCellArrow = @"GLCustomCellArrow";         // 箭头
NSString*_Nonnull GLCustomCellRadio = @"GLCustomCellRadio";         // 勾


static NSDictionary* staticDefaultAttributes = nil;
static NSDictionary* staticRegisterCellAttr = nil;


@interface GLCustomCell()<UITextFieldDelegate,UITextViewDelegate>{

    NSMutableArray* _componentKeys;
    NSMutableDictionary* _componentDictionary;
    
    UIColor* _badgeBgColor;
    
    NSString* _reuseIdentifier;
}
@property(nonatomic,weak)id<GLCustomCellDelegate> delegate;
@property(nonatomic,strong,nullable)UILabel* cellBadge;           //badge
@end

@implementation GLCustomCell

+ (void)initialize{
    [super initialize];
    staticDefaultAttributes = [self getDefaultAttributes];
}


+ (void)updateComponentAttributeByDictionary:(nonnull NSDictionary*)dict{
    if (!staticDefaultAttributes) {
        return;
    }
    if (!dict) {
        return;
    }
    NSMutableDictionary* tmpDict = [NSMutableDictionary dictionaryWithDictionary:staticDefaultAttributes];
    [tmpDict setValuesForKeysWithDictionary:dict];
    staticDefaultAttributes = tmpDict;
}

+ (void)registerCell:(nonnull NSArray*)componentKeys identifier:(nonnull NSString*)identifier bindData:(GLCustomCellRegister)bindBlock{
    [self registerCell:componentKeys identifier:identifier defaultAttributeConfig:nil bindData:bindBlock];
}

+ (void)registerCell:(nonnull NSArray*)componentKeys identifier:(nonnull NSString*)identifier defaultAttributeConfig:(GLCustomCellAttributionRegister)defaultConfig bindData:(GLCustomCellRegister)bindBlock
{
    if (!staticRegisterCellAttr) {
        staticRegisterCellAttr = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:0];
    dict = [@{
             @"componentKeys":componentKeys,
             @"bindBlock":bindBlock
             } mutableCopy];
    if (defaultConfig) {
        [dict setValue:defaultConfig forKey:@"defaultConfig"];

    }
    [staticRegisterCellAttr setValue:dict forKey:identifier];
}

+ (NSDictionary*)getDefaultAttributes{
    return @{

             GLCustomCellText:@{
                     @"font":GLCustomCell_Title_Font,
                     @"textColor":[UIColor blackColor],
                     },
             GLCustomCellGrayText:@{
                     @"font":GLCustomCell_Title_Font,
                     @"textColor":[UIColor grayColor],
                     },
             GLCustomCellText2:@{
                     @"font":GLCustomCell_Title_Font,
                     @"textColor":[UIColor blackColor],
                     },
             GLCustomCellCenterText:@{
                     @"font":GLCustomCell_Title_Font,
                     @"textColor":[UIColor blackColor],
                     @"textAlignment":@(NSTextAlignmentCenter),
                     },
             GLCustomCellSubText:@{
                     @"font":[UIFont systemFontOfSize:14],
                     @"textColor":[UIColor blackColor],
                     },
             GLCustomCellCatpionText:@{
                     @"font":GLCustomCell_Title_Font,
                     @"textColor":[UIColor grayColor],
                     @"textAlignment":@(NSTextAlignmentRight),
                     },
             //textField
             GLCustomCellInput:@{
                     @"font":GLCustomCell_Title_Font,
                     @"clearButtonMode":@(UITextFieldViewModeWhileEditing),
                     @"placeholder":@"请输入",
                     },
             GLCustomCellLeftNoEditInput:@{
                     @"font":GLCustomCell_Title_Font,
                     @"clearButtonMode":@(UITextFieldViewModeWhileEditing),
                     @"placeholder":@"请选择",
                     @"enabled":@(NO),
                     },
             GLCustomCellRightNoEditInput:@{
                     @"font":GLCustomCell_Title_Font,
                     @"clearButtonMode":@(UITextFieldViewModeWhileEditing),
                     @"placeholder":@"请选择",
                     @"textAlignment":@(NSTextAlignmentRight),
                     @"enabled":@(NO),
                     },
             //textView
             GLCustomCellTextView:@{
                     @"font":GLCustomCell_Title_Font,
                     },
             //badge
             GLCustomCellBadge:@{
                     @"font":[UIFont systemFontOfSize:14],
#ifdef GLS_COLOR_RED_E0563D
                     @"backgroundColor":GLS_COLOR_RED_E0563D,
#else
                     @"backgroundColor":[UIColor redColor],
#endif
                     },
             //button
             GLCustomCellButton:@{
                     @"titleLabel.font":[UIFont systemFontOfSize:14],
                     @"imageView.contentMode":@(UIViewContentModeScaleAspectFit),
                     @"titleColor":[UIColor blackColor],
                     },
             GLCustomCellButton2:@{
                     @"titleLabel.font":[UIFont systemFontOfSize:14],
                     @"imageView.contentMode":@(UIViewContentModeScaleAspectFit),
                     @"titleColor":[UIColor blackColor],
                     },
             GLCustomCellButton3:@{
                     @"titleLabel.font":[UIFont systemFontOfSize:14],
                     @"imageView.contentMode":@(UIViewContentModeScaleAspectFit),
                     @"titleColor":[UIColor blackColor],
                     },
             GLCustomCellButton4:@{
                     @"titleLabel.font":[UIFont systemFontOfSize:14],
                     @"imageView.contentMode":@(UIViewContentModeScaleAspectFit),
                     @"titleColor":[UIColor blackColor],
                     },
             GLCustomCellButton5:@{
                     @"titleLabel.font":[UIFont systemFontOfSize:14],
                     @"imageView.contentMode":@(UIViewContentModeScaleAspectFit),
                     @"titleColor":[UIColor blackColor],
                     },
             };
    
}
#pragma mark- lifeCycle
//重写，避免badge背景色在cell选中时变透明
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    
    if (self.cellBadge) {
        _badgeBgColor = self.cellBadge.backgroundColor;
    }
    [super setHighlighted:highlighted animated:animated];
    if (self.cellBadge) {
        self.cellBadge.backgroundColor = _badgeBgColor;
    }

}

-(void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
    if (self.cellBadge) {
        _badgeBgColor = self.cellBadge.backgroundColor;
    }

    [super setSelected:selected animated:animated];
    if (self.cellBadge) {
        self.cellBadge.backgroundColor = _badgeBgColor;
    }

}

-(void)setValue:(id)value forKeyPath:(NSString *)keyPath{
    if ([keyPath rangeOfString:@"GLCustomCell"].location != NSNotFound) {
        NSRange range = [keyPath rangeOfString:@"."];
        if (range.location != NSNotFound) {
            NSString* ckey = [keyPath substringToIndex:range.location];
            NSString* newKeyPath = [keyPath substringFromIndex:range.location+range.length];
            [self setComponentValue:value forComponenyKey:ckey forKeyPath:newKeyPath];
        }else{
            [self setComponentValue:value forComponenyKey:keyPath];
        }
    }else{
        [super setValue:value forKeyPath:keyPath];
    }
    
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _reuseIdentifier = reuseIdentifier;
    }
    return self;
}

- (nonnull instancetype)initWithIdentifier:(nonnull NSString *)identifier{
    NSDictionary* dict = [staticRegisterCellAttr valueForKey:identifier];
    NSArray* componentKeys = dict[@"componentKeys"];
    return [self initWithCustom:componentKeys reuseIdentifier:identifier delegate:nil];
}

- (instancetype)initWithCustom:(NSArray*)controlkeys reuseIdentifier:(NSString *)reuseIdentifier{
    return [self initWithCustom:controlkeys reuseIdentifier:reuseIdentifier delegate:nil];
    
}

- (nonnull instancetype)initWithCustom:(nonnull NSArray*)controlkeys reuseIdentifier:(nonnull NSString *)reuseIdentifier delegate:(id<GLCustomCellDelegate>)delegate{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self) {
        _reuseIdentifier = reuseIdentifier;
        self.delegate = delegate;
        [self addComponents:controlkeys];
        
        NSDictionary* dict = [staticRegisterCellAttr valueForKey:_reuseIdentifier];
        if (dict) {
            GLCustomCellAttributionRegister config = dict[@"defaultConfig"];
            if (config) {
                config(self);
            }
        }
        
    }
    return self;
}

#pragma mark- data ui init


/*
 * @description 默认组件显示宽高，当值为0时，根据内容自由分配
 */
-(CGSize)sizeByComponent:(UIView*)view{
    NSString* key = [self searchComponentKeyByComponent:view];
    return [self sizeByComponentKey:key];
}
-(CGSize)sizeByComponentKey:(GLComponentKey*)key{
    CGSize size = CGSizeZero;
    
    if ([key isEqualToString:GLCustomCellText]||
        [key isEqualToString:GLCustomCellText2]) {
        size = CGSizeMake(0, 25);
    }
    else if ([key isEqualToString:GLCustomCellGrayText]) {
        size = CGSizeMake(0, 25);
    }
    else if ([key isEqualToString:GLCustomCellCenterText]) {
        size = CGSizeMake(0, 25);
    }
    else if ([key isEqualToString:GLCustomCellSubText]) {
        size = CGSizeMake(0, 25);
    }
    else if ([key isEqualToString:GLCustomCellCatpionText]){
        size = CGSizeMake(0, 25);
    }
    else if ([key isEqualToString:GLCustomCellIcon]){
        size = CGSizeMake(25, 25);
    }
    else if ([key rangeOfString:GLCustomCellButton].location != NSNotFound){
        size = CGSizeMake(0, 22);
    }
    else if ([key isEqualToString:GLCustomCellIcon2]){
        size = CGSizeMake(20, 20);
    }
    else if ([key isEqualToString:GLCustomCellInput]||
             [key isEqualToString:GLCustomCellRightNoEditInput]||
             [key isEqualToString:GLCustomCellLeftNoEditInput]){
        size = CGSizeMake(0, 30);
    }

    
    if (self.delegate && [self.delegate respondsToSelector:@selector(size:size:commponentKey:)]) {
        size = [self.delegate size:_reuseIdentifier size:size commponentKey:key];
    }
    
    return size;
}

/*
 * @description 添加组件keys
 */
- (void)addComponents:(NSArray*)compoenents{
    if (!compoenents || compoenents.count == 0) {
        return;
    }
    if (!_componentKeys) {
        _componentKeys = [NSMutableArray arrayWithCapacity:0];
    }
    [_componentKeys addObjectsFromArray:compoenents];
    
    if (!_componentDictionary) {
        _componentDictionary = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    
    for (NSString* componentKey in _componentKeys) {
        if ([componentKey isKindOfClass:[NSArray class]]) {
            NSArray* subKeys = (NSArray*)componentKey;
            NSString* subContentStr = [NSString stringWithFormat:@"%@%ld",GLCustomCellSubConentKey,[_componentKeys indexOfObject:componentKey]];
            UIView* subContentV = [self subContentView];
            [self.contentView addSubview:subContentV];
            [_componentDictionary setValue:subContentV forKey:subContentStr];
            
            for (NSString* subComKey in subKeys) {
                UIView* controlView = [self controlByControlKey:subComKey];
                if ([controlView isKindOfClass:[NSNull class]]) {
                    continue;
                }
                [subContentV addSubview:controlView];
                [_componentDictionary setValue:controlView forKey:subComKey];
            }
        }else{
            UIView* controlView = [self controlByControlKey:componentKey];
            if ([controlView isKindOfClass:[NSNull class]]) {
                continue;
            }
            [self.contentView addSubview:controlView];
            [_componentDictionary setValue:controlView forKey:componentKey];
        }
        
    }
    
    if ([_componentKeys containsObject:GLCustomCellArrow]||[_componentKeys containsObject:GLCustomCellCenterText]) {
        self.selectionStyle = UITableViewCellSelectionStyleDefault;
    }else{
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [self setComponentAutoLayout];
}

-(BOOL)controlKeyIsExists:(NSString*)key{
    if (!key) {
        return NO;
    }
    for (NSString*a in _componentKeys) {
        if ([a isKindOfClass:[NSArray class]]) {
            NSArray* subArray = (NSArray*)a;
            for (NSString*sa in subArray) {
                if ([sa isEqualToString:key]) {
                    return YES;
                }
            }
        }
        else if ([a isEqualToString:key]) {
            return YES;
        }
    }
    return NO;
}

-(UIView*)subContentView{
    UIView* subContentV = [UIView new];
    subContentV.translatesAutoresizingMaskIntoConstraints = NO;
    return subContentV;
}
/*
 * @description 根据指定的key返回相应的组件
 */
-(id)controlByControlKey:(NSString*)key{

    UIView* controlV = [self searchComponentByComponentKey:key];
    if (controlV) {
        return controlV;
    }
    
    if ([key isEqualToString:GLCustomCellText]||
        [key isEqualToString:GLCustomCellText2]||
        [key isEqualToString:GLCustomCellGrayText]) {
        
        GLCustomLabel* textLab = [[GLCustomLabel alloc]init];
        textLab.backgroundColor = [UIColor whiteColor];
        textLab.translatesAutoresizingMaskIntoConstraints = NO;
        [textLab setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
        controlV = textLab;
    }
    else if ([key isEqualToString:GLCustomCellCenterText]||
             [key isEqualToString:GLCustomCellSubText]||
             [key isEqualToString:GLCustomCellCatpionText]) {
        
        GLCustomLabel* textLab = [[GLCustomLabel alloc]init];
        textLab.backgroundColor = [UIColor whiteColor];
        textLab.translatesAutoresizingMaskIntoConstraints = NO;
        controlV = textLab;
    }
    else if ([key isEqualToString:GLCustomCellIcon]||
             [key isEqualToString:GLCustomCellIcon2]){
        GLCustomImageView* iconImageV = [[GLCustomImageView alloc]init];
        iconImageV.backgroundColor = [UIColor whiteColor];
        iconImageV.contentMode = UIViewContentModeScaleToFill;
        iconImageV.translatesAutoresizingMaskIntoConstraints = NO;

        controlV = iconImageV;
    }
    else if ([key isEqualToString:GLCustomCellArrow]){
        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if ([key isEqualToString:GLCustomCellBadge]){
        GLBadgeLabel* label = [[GLBadgeLabel alloc]init];
        //不压缩，不扩大
        [label setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
        [label setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
        self.cellBadge = label;
        controlV = label;
    }
    else if ([key isEqualToString:GLCustomCellSwitch]){
        UISwitch* mySwitch = [[UISwitch alloc]init];
        mySwitch.translatesAutoresizingMaskIntoConstraints = NO;
        [mySwitch addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];

        controlV = mySwitch;
    }
    else if ([key isEqualToString:GLCustomCellInput]||
             [key isEqualToString:GLCustomCellRightNoEditInput]||
             [key isEqualToString:GLCustomCellLeftNoEditInput]){
        UITextField* inputField = [[UITextField alloc]init];
        inputField.backgroundColor = [UIColor whiteColor];
        inputField.translatesAutoresizingMaskIntoConstraints = NO;
        inputField.delegate = self;

        controlV = inputField;
    }
    else if ([key isEqualToString:GLCustomCellTextView]){
        UITextView* textView = [[UITextView alloc]init];
        textView.backgroundColor = [UIColor whiteColor];
        textView.delegate = self;
        textView.translatesAutoresizingMaskIntoConstraints = NO;
        controlV = textView;
    }
    else if ([key isEqualToString:GLCustomCellButton]||
             [key isEqualToString:GLCustomCellButton2]||
             [key isEqualToString:GLCustomCellButton3]||
             [key isEqualToString:GLCustomCellButton3]||
             [key isEqualToString:GLCustomCellButton4]){
        GLCustomButton* btn = [[GLCustomButton alloc]init];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        btn.translatesAutoresizingMaskIntoConstraints = NO;
        [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [btn setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
        [btn setContentHuggingPriority:UILayoutPriorityRequired+1 forAxis:UILayoutConstraintAxisHorizontal];
        CGFloat gap = 4;
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, -gap / 2, 0, gap / 2);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, gap / 2, 0 , - gap / 2);
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, gap / 2, 0, gap / 2);
        
        controlV = btn;
    }
    //根据配置属性定制
    NSDictionary* attributeDict = [staticDefaultAttributes valueForKey:key];
    if (attributeDict) {
        for (NSString* attrKey in attributeDict) {
            [controlV setValue:attributeDict[attrKey] forKeyPath:attrKey];
        }
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(customview:view:commponentKey:)]) {
        [self.delegate customview:_reuseIdentifier view:controlV commponentKey:key];
    }
    if (controlV) {
        return controlV;
    }
    
    return [NSNull null];
}




/*
 * @description 获取上个组件（左侧）
 */
-(UIView*)prevView:(UIView*)curView{
    NSArray* views = curView.superview.subviews;
    
    if (!views || views.count == 0) {
        return nil;
    }
    NSInteger index = [views indexOfObject:curView];
    index--;
    if (index < 0 || index > views.count -1) {
        return nil;
    }
    
    UIView* v = [views objectAtIndex:index];
    return v;
}

/*
 * @description 获取下个组件（右侧）
 */
-(UIView*)nextView:(UIView*)curView{
    NSArray* views = curView.superview.subviews;
    
    if (!views || views.count == 0) {
        return nil;
    }
    NSInteger index = [views indexOfObject:curView];
    index++;
    if (index < 0 || index > views.count -1) {
        return nil;
    }
    
    UIView* v = [views objectAtIndex:index];
    return v;
}

/*
 * @description 添加约束布局
 */
-(void)setComponentAutoLayout{
    
    UIView* superView = self.contentView;
    //一级
    for (UIView* curV in superView.subviews) {

        [curV mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            UIView* preV = [self prevView:curV];
            if (preV) {
                make.left.equalTo(preV.mas_right).offset(GLCustomCellControlMargin);
            }else{
                make.left.equalTo(superView).offset(GLCustomCellMargin).priority(UILayoutPriorityRequired);;
            }
            
            CGSize size = [self sizeByComponent:curV];
            if (size.width > 0) {
                make.width.mas_equalTo(size.width);
            }else{
                UIView* nextV = [self nextView:curV];
                if (!nextV){
                    CGFloat margin = GLCustomCellMargin;
                    if ([self controlKeyIsExists:GLCustomCellArrow]) {
                        margin = 0;
                    }
                    make.right.equalTo(superView).offset(-margin).priority(UILayoutPriorityRequired);
                }
                
            }
            if (size.height > 0) {
                make.height.mas_equalTo(size.height);
            }
            else if(![curV isKindOfClass:[GLBadgeLabel class]]){
                make.top.equalTo(superView).offset(GLCustomCellControlMargin);
                make.bottom.equalTo(superView).offset(-GLCustomCellControlMargin);
            }
            make.centerY.equalTo(superView);
            
        }];
        //二级
        if ([curV isMemberOfClass:[UIView class]]) {
//            curV.backgroundColor = [UIColor greenColor];
//            NSArray* colors = @[[UIColor redColor],[UIColor blueColor],[UIColor orangeColor]];
            for (UIView* subcv in curV.subviews) {
//                subcv.backgroundColor = colors[[curV.subviews indexOfObject:subcv]];
                [subcv mas_makeConstraints:^(MASConstraintMaker *make) {
                    //
                    UIView* spreV = [self prevView:subcv];
                    if (spreV) {
                        make.top.equalTo(spreV.mas_bottom);
                    }else{
                        make.top.equalTo(curV);
                    }
                    make.left.equalTo(curV);
                    
                    CGSize size = [self sizeByComponent:subcv];
                    if (size.width > 0) {
                        make.width.mas_equalTo(size.width);
                    }else{
                        make.right.equalTo(curV);
                    }
                    
                    if (size.height > 0) {
                        make.height.mas_equalTo(size.height);
                    }
                    else if(![curV isKindOfClass:[GLBadgeLabel class]]){
                        UIView* nextV = [self nextView:subcv];
                        if (!nextV) {
                            make.bottom.equalTo(curV.mas_bottom);
                        }
                        
                    }
                    

                }];
            }

        }
    }
    
}



-(UIView*)searchComponentByComponentKey:(NSString*)key{
    
    id controlView = [_componentDictionary valueForKey:key];
    if (nil != controlView && ![controlView isKindOfClass:[NSNull class]]) {
        return controlView;
    }
    
    return nil;
}

-(NSString*)searchComponentKeyByComponent:(UIView*)view{
    
    NSArray* keys = [_componentDictionary allKeys];
    for (NSString* key in keys) {
        UIView* v = [_componentDictionary valueForKey:key];
        if (v == view) {
            return key;
        }
    }

    
    return nil;
}

#pragma mark- API
- (void)updateCellByModel:(nonnull id)obj{
    NSDictionary* dict = [staticRegisterCellAttr valueForKey:self.reuseIdentifier];
    GLCustomCellRegister dataBindBlock = [dict valueForKey:@"bindBlock"];
    if (dataBindBlock) {
        dataBindBlock(self,obj);
    }
}

- (void)setComponentValue:(id)value forComponenyKey:(GLComponentKey *)ckey{
    if (!ckey) {
        return;
    }
    

    UIView* view = [_componentDictionary valueForKey:ckey];
    
    if (view) {
        if ([view isKindOfClass:[UILabel class]]) {
            UILabel* textLab = (UILabel*)view;
            textLab.text = value;
            
            if ([view isMemberOfClass:[GLBadgeLabel class]]) {
                [textLab sizeToFit];
                NSString* stringValue = (NSString*)value;
                if (stringValue && stringValue.length > 0) {
                    textLab.hidden = NO;
                }else{
                    textLab.hidden = YES;
                }
            }
        }
        else if ([view isKindOfClass:[UISwitch class]]){
            UISwitch* theSwitch = (UISwitch*)view;
            theSwitch.on = [value boolValue];
        }
        else if ([view isKindOfClass:[UIImageView class]]){
            if ([value isKindOfClass:[NSString class]]) {
                value = [UIImage imageNamed:value];
                if (!value) {
                    return;
                }
            }
            UIImageView* imgV = (UIImageView*)view;
            imgV.image = value;
        }
        else if ([view isKindOfClass:[UITextField class]]){
            UITextField* inputField = (UITextField*)view;
            inputField.text = value;
        }
        else if ([view isKindOfClass:[UITextView class]]){
            UITextView* textView = (UITextView*)view;
            textView.text = value;
        }
        else if ([view isKindOfClass:[UIButton class]]){
            UIButton* btn = (UIButton*)view;
            if ([value isKindOfClass:[NSString class]]) {
                 [btn setTitle:value forState:UIControlStateNormal];
            }
            else{
                [btn setImage:value forState:UIControlStateNormal];
            }
            [btn sizeToFit];
        }
        
    }
    else if ([ckey isEqualToString:GLCustomCellRadio]){
        if ([value boolValue]) {
            self.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
            self.accessoryType = UITableViewCellAccessoryNone;
        }

    }
}

- (void)setComponentValuesForKeys:(nonnull NSDictionary*)dict{
    for (NSString* key in dict) {
        [self setValue:dict[key] forKeyPath:key];
    }
}

- (void)setComponentValue:(nullable id)value forComponenyKey:(nonnull GLComponentKey *)ckey forKeyPath:(nonnull NSString*)key{
    if (!ckey) {
        return;
    }
    if (!key) {
        [self setComponentValue:value forComponenyKey:ckey];
    }
    
    UIView* view = [_componentDictionary valueForKey:ckey];
    if (!view && [ckey isEqualToString:GLCustomCellSelf]) {
        view = self;
    }
    if (!view) {
        return;
    }
    
    [view setValue:value forKeyPath:key];
}

- (id)getComponentValueByKey:(GLComponentKey*)key{
    if (!key) {
        return nil;
    }
    
    UIView* view = [_componentDictionary valueForKey:key];
    if (view) {
        if ([view isKindOfClass:[UILabel class]]) {
            UILabel* textLab = (UILabel*)view;
            return textLab.text;
            
        }
        else if ([view isKindOfClass:[UISwitch class]]){
            UISwitch* theSwitch = (UISwitch*)view;
            return [NSNumber numberWithBool:theSwitch.on];
        }
        else if ([view isKindOfClass:[UITextField class]]){
            UITextField* inputField = (UITextField*)view;
            return inputField.text;
        }
        else if ([view isKindOfClass:[UITextView class]]){
            UITextView* textView = (UITextView*)view;
            return textView.text;
        }
        
        
    }
    else if ([key isEqualToString:GLCustomCellRadio]){
        if (self.accessoryType == UITableViewCellAccessoryCheckmark) {
            return [NSNumber numberWithBool:YES];
        }else{
            return [NSNumber numberWithBool:NO];
        }
    }
    
    return nil;
}


-(void)buttonClicked:(UIButton*)btn{
    NSString* key = [self searchComponentKeyByComponent:btn];
    if (!key) {
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(buttonClicked:commponentKey:)]) {
        [self.delegate buttonClicked:self commponentKey:key];
    }
    [self clicked:btn subTag:key];
}

-(void)switchValueChanged:(UISwitch*)s{

    if (self.delegate && [self.delegate respondsToSelector:@selector(valueDidChanged:commponentKey:newValue:)]) {
        [self.delegate valueDidChanged:self commponentKey:GLCustomCellSwitch newValue:[NSNumber numberWithBool:s.on]];
    }
    [self valueDidChanged:[NSNumber numberWithBool:s.on]];
}

#pragma mark- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString* newStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.delegate && [self.delegate respondsToSelector:@selector(valueDidChanged:commponentKey:newValue:)]) {
        [self.delegate valueDidChanged:self commponentKey:GLCustomCellInput newValue:newStr];
    }
    [self valueDidChanged:newStr];
    return YES;
}
#pragma mark- UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString* newStr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if (self.delegate && [self.delegate respondsToSelector:@selector(valueDidChanged:commponentKey:newValue:)]) {
        [self.delegate valueDidChanged:self commponentKey:GLCustomCellTextView newValue:newStr];
    }
    [self valueDidChanged:newStr];
    return YES;
}

#pragma mark- GLFormBaseCell override
-(void)setRowValue:(id)value{
    [super setRowValue:value];
    if (self.valueKey) {
        [self setComponentValue:value forComponenyKey:self.valueKey];
    }
}
-(id)rowValue{
    if (self.valueKey) {
        return [self getComponentValueByKey:self.valueKey];
    }
    return nil;
}
-(void)clicked:(id)sender subTag:(NSString*)tag{
    [super clicked:sender subTag:tag];
}

#pragma mark- setter and getter


@end

#pragma mark- custom commponents
@implementation GLCustomImageView
-(void)setUrl:(NSURL *)url{
#if __has_include("UIImdageView+WebCache.h")
    [self sd_setImageWithURL:url placeholderImage:nil];
#else
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:url];
        UIImage* image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.image = image;
        });
    });
    
#endif
}
-(void)setImageName:(NSString *)imageName{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage* image = [UIImage imageNamed:imageName];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.image = image;
        });
    });
}
-(void)setImagePath:(NSString *)imagePath{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.image = image;
        });
    });
}

-(void)setSize:(CGSize)size{
    _size = size;
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        if (_size.width > 0) {
            make.size.mas_equalTo(_size.width);
        }
        if (_size.height > 0) {
            make.size.mas_equalTo(_size.height);
        }
    }];
}
@end


@implementation GLCustomButton
-(void)setImage:(UIImage *)image{
    [self setImage:image forState:UIControlStateNormal];
}

-(void)setImageName:(NSString *)imageName{
    UIImage* image = [UIImage imageNamed:imageName];
    [self setImage:image forState:UIControlStateNormal];
}

-(void)setImagePath:(NSString *)imagePath{
    UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
    [self setImage:image forState:UIControlStateNormal];
}

-(void)setSelectedImage:(UIImage *)selectedImage{
    [self setImage:selectedImage forState:UIControlStateSelected];
}

-(void)setSelectedImageName:(NSString *)selectedImageName{
    UIImage* image = [UIImage imageNamed:selectedImageName];
    [self setImage:image forState:UIControlStateSelected];
}

-(void)setSelectedImagePath:(NSString *)selectedImagePath{
    UIImage* image = [UIImage imageWithContentsOfFile:selectedImagePath];
    [self setImage:image forState:UIControlStateSelected];
}


-(void)setTitle:(NSString *)title{
    [self setTitle:title forState:UIControlStateNormal];
}

-(void)setTitleColor:(UIColor *)titleColor{
    [self setTitleColor:titleColor forState:UIControlStateNormal];
}

-(void)setSelectedTitle:(NSString *)selectedTitle{
    [self setTitle:selectedTitle forState:UIControlStateSelected];
}

-(void)setSelectedTitleColor:(UIColor *)selectedTitleColor{
    [self setTitleColor:selectedTitleColor forState:UIControlStateSelected];
}


-(void)setSize:(CGSize)size{
    _size = size;
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        if (_size.width > 0) {
            make.size.mas_equalTo(_size.width);
        }
        if (_size.height > 0) {
            make.size.mas_equalTo(_size.height);
        }
    }];
}
@end

@implementation GLCustomLabel
-(void)setLimitWordNumber:(NSInteger)limitWordNumber{
    if (_limitWordNumber != limitWordNumber) {
        _limitWordNumber = limitWordNumber;
        
        NSMutableString* widthStr  = [NSMutableString stringWithCapacity:0];
        for (NSInteger index = 0; index < _limitWordNumber; index++) {
            [widthStr appendString:@"中"];
        }
        NSMutableDictionary *attrsDict = [NSMutableDictionary dictionary];
        attrsDict[NSFontAttributeName] = self.font;
        
        CGFloat width = [widthStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 25) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrsDict context:nil].size.width+1.0f;
        
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width);
        }];
    }
    
}

-(void)setSize:(CGSize)size{
    _size = size;
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        if (_size.width > 0) {
            make.size.mas_equalTo(_size.width);
        }
        if (_size.height > 0) {
            make.size.mas_equalTo(_size.height);
        }
    }];
}
@end
